﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace HWR_Ants.Classes
{
    public class MapWrapper
    {
        private Dictionary<string, City> _Cities = new Dictionary<string, City>();
        private List<Road> _Roads = new List<Road>();

        public MapWrapper(SortedList<string, Point> listOfTSPCities)
        {
            foreach (KeyValuePair<string, Point> p in listOfTSPCities)
            {
                AddCity(p.Key, p.Value);
            }

            IList<Point> points = listOfTSPCities.Values;

            for (int i = 0; i < points.Count - 1; i++)
            {
                for (int j = i + 1; j < points.Count; j++)
                {
                    KeyValuePair<string, Point> kvp_from = listOfTSPCities.ElementAt(i);
                    KeyValuePair<string, Point> kvp_to = listOfTSPCities.ElementAt(j);
                    AddRoad(kvp_from, kvp_to);
                }
            }
        }

        public IEnumerable<City> Cities
        {
            get { return _Cities.Values; }
        }

        public IEnumerable<Road> Roads
        {
            get { return _Roads; }
        }

        private City AddCity(string name, Point point)
        {
            City c = new City(name, point);
            _Cities.Add(name, c);
            return c;
        }

        public Road AddRoad(KeyValuePair<string, Point> from, KeyValuePair<string, Point> to)
        {
            double distance = Pythagoras(from.Value, to.Value);

            if (distance == 0)
            {
                //TODO: hier distance bei gleichen Punkten
                // Points are equal
                // set to 0.01
                distance = 0.01;
            }

            City from_city = null;
            if (!_Cities.TryGetValue(from.Key, out from_city))
            {
                from_city = AddCity(from.Key,from.Value);
            }

            City to_city = null;
            if (!_Cities.TryGetValue(to.Key, out to_city))
            {
                to_city = AddCity(to.Key, to.Value);
            }

            return AddRoad(distance, from_city, to_city);
        }

        public Road AddRoad(double distance, City from, City to)
        {
            Road road = new Road(distance);
            from.AddRoad(road, to);
            to.AddRoad(road, from);
            _Roads.Add(road);
            return road;
        }

        private double Pythagoras(Point p1, Point p2)
        {
            return Math.Sqrt(Math.Pow((p1.X - p2.X), 2) + Math.Pow((p1.Y - p2.Y), 2));
        }
        
    }
}
